package business

import (
	"encoding/json"
	"ginBasic/app/common/lib"
	"ginBasic/app/common/model"
	"ginBasic/app/common/model/filter"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

var Login = new(LoginBus)

type LoginBus struct {
	BaseBus
}

func (b LoginBus) DoLogin(req model.Login, c *gin.Context) (flag bool, msg string) {

	userInfo := model.ManagerModel.GetUserByUsername(req.UserName)

	if userInfo.Username == "" || userInfo.Password == "" {
		return false, "用户不存在"
	}
	//判断密码是否正确
	password := lib.Md5(req.Password)
	if userInfo.Password != password {
		return false, "密码不正确"
	}
	//保存信息到session
	//3、执行登录 保存用户信息 执行跳转
	session := sessions.Default(c)
	//注意：session.Set没法直接保存结构体对应的切片 把结构体转换成json字符串
	userinfoSlice, _ := json.Marshal(filter.ManagerS{
		Id:       userInfo.Id,
		Username: userInfo.Username,
		Mobile:   userInfo.Mobile,
		Email:    userInfo.Email,
		Status:   userInfo.Status,
		RoleId:   userInfo.RoleId,
		IsSuper:  userInfo.IsSuper,
	})
	session.Set("userinfo", string(userinfoSlice))
	session.Save()

	return true, "登录成功"
}
